
#include <BViewer>
#include <BRoundHandler>
#include <BSurface>
#include <BSphere>
#include <BCamera>
#include <BViewer>
#include <BScene>
#include <BProgram>
#include <BMaterial>
#include <BHBoxLayout>
#include <BVBoxLayout>
#include <BGeometry>
#include <BIcon>
#include <BButton>
#include <BApplication>

#include "MainDialog.h"

const char* shaderVertSource = R"(
varying vec4	color;
varying float 	diffuse;
void main(void)
{
	color = gl_Vertex;
	gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
	vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
	vec3 light = normalize(gl_LightSource[0].position.xyz);
	diffuse = max(dot(normal, light), 0.8);
}
)";
const char* shaderFragSource = R"(
varying vec4	color;
varying float 	diffuse;
void main(void)
{
	gl_FragColor = clamp(color, 0.0, 1.0) * diffuse;
}
)";

MainDialog::MainDialog(const BString& title, BWidget* parent) : BDialog(parent)
{
	const BString& currentPath = BApplication::currentPath();

	this->setTitle(title);
	BButton* maxButton = new BButton();
	maxButton->setName("max");
	maxButton->setAsset(Button_Maximize);
	maxButton->setIconSize(32);
	this->insertTitleButton(0, maxButton);

	_scene = new BScene();

	BLight* light = new BLight();
	{
		light->setAmbient(36, 36, 36);
		light->setDiffuse(255, 255, 255);
		light->setSpecular(255, 100, 100);
		light->setPosition(0, -30, 30);
		//_scene->insert(light);
	}

	BNode* node = new BNode();
	{
		BProgram* program = new BProgram();

		BShader* shaderVert = new BShader(BShader::Type_Vertex);
		shaderVert->setText(shaderVertSource);
		program->addShader(shaderVert);

		BShader* shaderFrag = new BShader(BShader::Type_Fragment);
		shaderFrag->setText(shaderFragSource);
		program->addShader(shaderFrag);

		BSphere* sphere = new BSphere(5, 20, 20);
		sphere->setProgram(program);

		BMaterial* mate = new BMaterial;
		mate->setAmbient(BColor(66, 66, 66, 128));
		mate->setDiffuse(BColor(96, 136, 136, 128));
		mate->setSpecular(BColor(96, 136, 136, 128));
		mate->setShininess(200);
		sphere->setMaterial(mate);

		node->insertShape(sphere);
		_scene->insert(node);
	}

	BCameraHolder camera = new BCamera();
	camera->setPosition(30, 30, 30);
	camera->setCenter(0, 0, 0);

	BViewer* viewer = new BViewer();
	viewer->setScene(_scene);
	viewer->setCamera(camera);
	viewer->setHandler(new BRoundHandler);
	viewer->setStyleSheet("background-color:rgb(66, 66, 66)");

	BVBoxLayout* editLayout = new BVBoxLayout();
	editLayout->setSplitable(true);
	editLayout->setSpacing(5);
	editLayout->setHandleSize(3);
	{
		_vertexShaderEdit = new ShaderEdit();
		_vertexShaderEdit->setText(shaderVertSource);

		_pixelShaderEdit = new ShaderEdit();
		_pixelShaderEdit->setText(shaderFragSource);

		editLayout->addWidget(_vertexShaderEdit);
		editLayout->addWidget(_pixelShaderEdit);
	}

	BHBoxLayout* hlayout = new BHBoxLayout(this);
	hlayout->setSplitable(true);
	hlayout->setSpacing(10);
	hlayout->addWidget(viewer);
	hlayout->addLayout(editLayout);
}
MainDialog::~MainDialog()
{

}
